package com.cos.hospital.ui.main;

import android.content.Intent;
import android.graphics.Color;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Vibrator;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;

import com.blankj.utilcode.util.CacheDiskUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.cos.hospital.R;
import com.cos.hospital.code.Code;
import com.cos.hospital.code.QueryType;
import com.cos.hospital.code.helper.MyOnFreshListener;
import com.cos.hospital.model.UHttp;
import com.cos.hospital.model.bean.ErrorBean;
import com.cos.hospital.model.bean.PatientListBean;
import com.cos.hospital.model.bean.ResultBean;
import com.cos.hospital.model.connector.HttpMsgListener;
import com.cos.hospital.model.event.CureListUpdateEvent;
import com.cos.hospital.model.event.DoSearchEvent;
import com.cos.hospital.model.event.ReceptionPersonNumEvent;
import com.cos.hospital.model.event.SearchContentEvent;
import com.cos.hospital.model.retrofit.HostWrapper;
import com.cos.hospital.model.retrofit.MyObserver;
import com.cos.hospital.model.retrofit.RequestServes;
import com.cos.hospital.tool.MyUtil;
import com.cos.hospital.tool.SPUtil;
import com.cos.hospital.tool.SurplusTimeComparator;
import com.cos.hospital.tool.UDate;
import com.cos.hospital.tool.USnackbar;
import com.cos.hospital.tool.UToast;
import com.cos.hospital.tool.UTxt;
import com.cos.hospital.ui.main.adapter.CureAdapter;
import com.cos.hospital.ui.patient.SearchAcitvity;
import com.cos.hospital.ui.record.RecordCode;
import com.cos.hospital.ui.record.edit.EditorAcupointActivity;
import com.cos.hospital.widget.MyDividerDecoration;
import com.google.gson.JsonObject;
import com.jude.utils.JUtils;
import com.liaoinstan.springview.container.DefaultHeader;
import com.liaoinstan.springview.widget.SpringView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

import static android.content.Context.VIBRATOR_SERVICE;

/**
 * author: zc
 * date On :2019/3/5
 * description:
 */
public class CureOneFragment extends MainFragment {
    @BindView(R.id.springView)
    SpringView springView;
    @BindView(R.id.rc)
    RecyclerView rc;
    private ArrayList<PatientListBean.ItemsBean> list;
    private BaseQuickAdapter adapter;
    private int pageIndex = 1;
    private SurplusTimeComparator surplusTimeComparator;
    private int searchResultOldPositon = -1;

    private int queryType;

    public CureOneFragment(int queryType) {
        this.queryType = queryType;
    }

    @Override
    protected int layout() {
        return R.layout.frag_cure;
    }

    @Override
    protected void init() {
        springView.setHeader(new DefaultHeader(context));
        list = new ArrayList<>();
        adapter = new CureAdapter(list);
        adapter.openLoadAnimation();//开启默认动画AlphaInAnimation
        rc.setLayoutManager(new LinearLayoutManager(context));
        adapter.setEmptyView(R.layout.lay_empty, rc);//设置当list中元素个数为0时显示的布局
        rc.addItemDecoration(new MyDividerDecoration(Color.TRANSPARENT, JUtils.dip2px(8)));
        rc.setAdapter(adapter);
        surplusTimeComparator = new SurplusTimeComparator();
    }

    @Override
    protected void logic() {
        springView.setListener(new MyOnFreshListener() {
            @Override
            public void onRefresh() {
                pageIndex = 1;
                getList();
            }
        });
        adapter.setOnItemClickListener((adapter, view, position) -> toEditAcupoint(position));
        adapter.setOnLoadMoreListener(() -> {
            pageIndex++;
            getList();
        }, rc);
        springView.callFreshDelay();
        Observable.interval(1000, TimeUnit.MILLISECONDS)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new MyObserver<Long>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        addEvent(d);
                    }

                    @Override
                    public void onNext(Long aLong) {
                        gogogo();
                        adapter.notifyDataSetChanged();
                    }
                });
    }

    private void gogogo() {
        for (PatientListBean.ItemsBean itemsBean : list) {
            int fldTreatmentState = itemsBean.getFldTreatmentState();
            String fldTreatmentStart = itemsBean.getFldTreatmentStart();
            int fldTreatmentDuration = itemsBean.getFldTreatmentDuration();
            Date date = UDate.strToDateSafety(fldTreatmentStart);
            long surplus = date.getTime() / 1000 + fldTreatmentDuration * 60 - System.currentTimeMillis() / 1000;//剩余时间（秒）
            if (!itemsBean.isEnd() && fldTreatmentState != 2) {//非本地判断结束切非后台返回结束
                if (surplus <= 0) {//剩余时间大于0秒
                    cureFinish(itemsBean);//请求接口：治疗结束
                    itemsBean.setEnd(true);//本地判断结束
                }
            }
        }
    }

    private void cureFinish(PatientListBean.ItemsBean item) {
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("fldMedicalHistoryId", item.getFldMedicalHistoryId());
        jsonObject.addProperty("fldEditId", SPUtil.getUserId());
        UHttp.start(HostWrapper.with().create(RequestServes.class).cureFinish(jsonObject), "治疗结束", new HttpMsgListener<ResultBean>() {
            @Override
            public void onSubscribe(Disposable disposable) {
                compositeDisposable.add(disposable);
            }

            @Override
            public void onError(String describe) {
                UToast.toast(describe);
            }

            @Override
            public void onSuccess(ResultBean dto) {
                if (dto.isSuccess()) {
                    item.setFldTreatmentState(2);

                    Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
                    Ringtone r = RingtoneManager.getRingtone(getContext(), notification);
                    r.play();

                    Intent intent = new Intent(Code.Broadcast.CUREEND);
                    intent.putExtra(Code.SP.CONTENT, item.getFldPatientName() + "治疗结束");
                    context.sendBroadcast(intent);
                    Vibrator vibrator = (Vibrator) getContext().getSystemService(VIBRATOR_SERVICE);
                    vibrator.vibrate(1000);

                    EventBus.getDefault().post(new CureListUpdateEvent());
                } else {
                    ErrorBean errorBean = dto.getError();
                    if (errorBean != null) {
                        UToast.toast(UTxt.isNull(errorBean.getMessage(), Code.DefaultPrompt));
                    }
                }
            }
        });
    }

    private void getList() {
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("keyword", "");
        jsonObject.addProperty("fldDoctorId", SPUtil.getUserId());
        jsonObject.addProperty("pageIndex", pageIndex);
        jsonObject.addProperty("pageSize", 10);
        jsonObject.addProperty("queryType", queryType);
        ReceptionPersonNumEvent receptionPersonNumEvent = new ReceptionPersonNumEvent();
        receptionPersonNumEvent.queryType = queryType;
        UHttp.start(getServes().getCureList(jsonObject), "治疗管理列表", new HttpMsgListener<ResultBean<PatientListBean>>() {
            @Override
            public void onSubscribe(Disposable disposable) {
                addEvent(disposable);
            }

            @Override
            public void onError(String describe) {
                USnackbar.showWarning(context, describe);
            }

            @Override
            public void onFinish() {
                springView.onFinishFreshAndLoadDelay();
            }

            @Override
            public void onSuccess(ResultBean<PatientListBean> dto) {
                if (dto.isSuccess()) {
                    PatientListBean resultBean = dto.getResult();
                    if (resultBean != null) {
                        int pageIndex = resultBean.getPageIndex();
                        int pageSize = resultBean.getPageSize();
                        int recordCount = resultBean.getRecordCount();
                        if (pageIndex == 1) {
                            searchResultOldPositon = -1;
                            list.clear();
                            adapter.notifyDataSetChanged();
                        }
                        List<PatientListBean.ItemsBean> itemsBeanList = resultBean.getItems();
                        if (itemsBeanList != null && itemsBeanList.size() != 0) {
                            list.addAll(itemsBeanList);
                            Collections.sort(list, surplusTimeComparator);
                        }
                        int totalPageCount = MyUtil.getInstance().getTotalPageCount(pageSize, recordCount);
                        if (totalPageCount <= pageIndex) {
                            adapter.loadMoreEnd();
                        } else {
                            adapter.loadMoreComplete();
                        }
                    }
                } else {
                    if (pageIndex == 1) {
                        list.clear();
                        adapter.notifyDataSetChanged();
                    }
                    ErrorBean errorBean = dto.getError();
                    if (errorBean != null) {
                        showNotice(UTxt.isNull(errorBean.getMessage(), Code.DefaultPrompt));
                    } else {
                        showNotice(Code.DefaultPrompt);
                    }
                }
                receptionPersonNumEvent.perosnNum = adapter.getData().size();
                EventBus.getDefault().post(receptionPersonNumEvent);
            }
        });
    }

    private void toEditAcupoint(int position) {
        CacheDiskUtils.getInstance().put("CureOneFragment", list);

        PatientListBean.ItemsBean itemsBean = list.get(position);
        Intent intent = new Intent(context, EditorAcupointActivity.class);
        intent.putExtra(Code.SP.FLDELEID, RecordCode.Type.AcupunctureRecord);
        intent.putExtra(Code.SP.FLDTREATMENTSTATE, itemsBean.getFldTreatmentState());
        intent.putExtra(Code.SP.FLDMEDICALHISTORYID, itemsBean.getFldMedicalHistoryId());
        intent.putExtra(Code.SP.FLDDOCTORID, itemsBean.getFldDoctorId());
        intent.putExtra(Code.SP.FLDNAME, itemsBean.getFldPatientName());
        intent.putExtra(Code.SP.FLDSEX, itemsBean.getFldPatientSex());
        intent.putExtra(Code.SP.FLDAGE, itemsBean.getFldAge());
        intent.putExtra(Code.SP.FLDCREATETIME, itemsBean.getFldCreateTime());
        intent.putExtra(Code.SP.FLDMEDICALNUM, itemsBean.getFldMedicalNum());
        intent.putExtra(Code.SP.FLDDOCTORNAME, itemsBean.getFldCustomerName());

        intent.putExtra(EditorAcupointActivity.DATA_LIST_KEY,"CureOneFragment");
        startActivity(intent);
    }

    private void doSearch(String content) {
        MyUtil.getInstance().closeInputMethod(getActivity());
        for (int position = 0; position < list.size(); position++) {
            PatientListBean.ItemsBean itemsBean = list.get(position);
            String fldPatientName = itemsBean.getFldPatientName();
            String fldMedicalNum = itemsBean.getFldMedicalNum();
            String fldPatientPhone = itemsBean.getFldPatientPhone();
            if (fldPatientName.equals(content) || fldMedicalNum.equals(content) || fldPatientPhone.equals(content)) {
                searchResultOldPositon = position;
                changeItem(itemsBean, true);
                ((LinearLayoutManager) rc.getLayoutManager()).scrollToPositionWithOffset(position, 0);
                return;
            }
        }
        Intent intent = new Intent(context, SearchAcitvity.class);
        intent.putExtra(Code.SP.CONTENT, content);
        intent.putExtra(Code.SP.FROMCURE, true);
        startActivity(intent);
    }

    private void changeItem(PatientListBean.ItemsBean itemsBean, boolean searchResult) {
        itemsBean.setSearchResult(searchResult);
        adapter.notifyItemChanged(searchResultOldPositon);
    }


    @Override
    protected void refresh() {
        if (springView != null) {
            springView.callFreshDelay(200);
        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void update(CureListUpdateEvent event) {
        pageIndex = 1;
        getList();
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        EventBus.getDefault().register(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void updateInfo(DoSearchEvent event) {
        if (event != null) {
            if (event.queryType == QueryType.CUREING) {
                doSearch(event.content);
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void updateInfo(SearchContentEvent event) {
        if (event != null) {
            if (event.queryType == QueryType.CUREING) {
                if (event.txtEnd.length() == 0) {
                    if (searchResultOldPositon == -1) {
                        return;
                    }
                    if (list.size() == 0) {
                        return;
                    }
                    PatientListBean.ItemsBean itemsBean = list.get(searchResultOldPositon);
                    if (itemsBean == null) {
                        return;
                    }
                    changeItem(itemsBean, false);
                    searchResultOldPositon = -1;
                }
            }
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
